{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "ad3e99e0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "数据加载成功！\n",
      "数据形状: (569, 7)\n",
      "\n",
      "数据前5行:\n",
      "     最大周长   最大凹陷度    平均凹陷度    最大面积   最大半径  平均灰度值  肿瘤性质\n",
      "0  184.60  0.2654  0.14710  2019.0  25.38  17.33     0\n",
      "1  158.80  0.1860  0.07017  1956.0  24.99  23.41     0\n",
      "2  152.50  0.2430  0.12790  1709.0  23.57  25.53     1\n",
      "3   98.87  0.2575  0.10520   567.7  14.91  26.50     0\n",
      "4  152.20  0.1625  0.10430  1575.0  22.54  16.67     0\n",
      "\n",
      "数据基本信息:\n",
      "<class 'pandas.core.frame.DataFrame'>\n",
      "RangeIndex: 569 entries, 0 to 568\n",
      "Data columns (total 7 columns):\n",
      " #   Column  Non-Null Count  Dtype  \n",
      "---  ------  --------------  -----  \n",
      " 0   最大周长    569 non-null    float64\n",
      " 1   最大凹陷度   569 non-null    float64\n",
      " 2   平均凹陷度   569 non-null    float64\n",
      " 3   最大面积    569 non-null    float64\n",
      " 4   最大半径    569 non-null    float64\n",
      " 5   平均灰度值   569 non-null    float64\n",
      " 6   肿瘤性质    569 non-null    int64  \n",
      "dtypes: float64(6), int64(1)\n",
      "memory usage: 31.2 KB\n",
      "None\n",
      "\n",
      "目标变量分布:\n",
      "肿瘤性质\n",
      "1    358\n",
      "0    211\n",
      "Name: count, dtype: int64\n",
      "\n",
      "训练集大小: (455, 6)\n",
      "测试集大小: (114, 6)\n",
      "\n",
      "模型训练完成！\n",
      "\n",
      "模型准确率: 0.9737\n",
      "\n",
      "详细分类报告:\n",
      "              precision    recall  f1-score   support\n",
      "\n",
      "           0       0.98      0.95      0.96        42\n",
      "           1       0.97      0.99      0.98        72\n",
      "\n",
      "    accuracy                           0.97       114\n",
      "   macro avg       0.97      0.97      0.97       114\n",
      "weighted avg       0.97      0.97      0.97       114\n",
      "\n",
      "\n",
      "各类别的特征均值:\n",
      "类别 0: [1.01059738 0.9988295  0.95070885 0.95838646 1.0111839  0.58707526]\n",
      "类别 1: [-0.59901163 -0.61040707 -0.58896606 -0.56105674 -0.59421701 -0.33343453]\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.naive_bayes import GaussianNB\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn.metrics import accuracy_score, classification_report\n",
    "import warnings\n",
    "\n",
    "# 过滤警告\n",
    "warnings.filterwarnings('ignore')\n",
    "\n",
    "# 1. 数据加载\n",
    "try:\n",
    "    df = pd.read_excel(\"D:\\贺之恒的python\\pppython\\python商业数据分析\\@Python大数据分析与机器学习商业案例实战\\第6章 朴素贝叶斯模型\\源代码汇总_PyCharm格式\\肿瘤数据.xlsx\")\n",
    "    print(\"数据加载成功！\")\n",
    "    print(f\"数据形状: {df.shape}\")\n",
    "except FileNotFoundError:\n",
    "    print(\"错误：未找到数据文件！\")\n",
    "    exit()\n",
    "\n",
    "# 2. 数据探索\n",
    "print(\"\\n数据前5行:\")\n",
    "print(df.head())\n",
    "print(\"\\n数据基本信息:\")\n",
    "print(df.info())\n",
    "print(\"\\n目标变量分布:\")\n",
    "print(df['肿瘤性质'].value_counts())\n",
    "\n",
    "# 3. 划分特征变量和目标变量\n",
    "X = df.drop(columns='肿瘤性质') \n",
    "y = df['肿瘤性质']\n",
    "\n",
    "# 4. 数据预处理\n",
    "# 检查缺失值\n",
    "if df.isnull().sum().any():\n",
    "    print(\"\\n发现缺失值，进行填充处理...\")\n",
    "    X = X.fillna(X.mean())  # 数值型缺失值用均值填充\n",
    "\n",
    "# 特征标准化（朴素贝叶斯虽然不强制要求，但有时会有帮助）\n",
    "scaler = StandardScaler()\n",
    "X_scaled = scaler.fit_transform(X)\n",
    "\n",
    "# 5. 划分训练集和测试集\n",
    "X_train, X_test, y_train, y_test = train_test_split(\n",
    "    X_scaled, y, \n",
    "    test_size=0.2, \n",
    "    random_state=42,  # 修改随机种子以便结果可重现\n",
    "    stratify=y  # 保持训练集和测试集中各类别比例一致\n",
    ")\n",
    "\n",
    "print(f\"\\n训练集大小: {X_train.shape}\")\n",
    "print(f\"测试集大小: {X_test.shape}\")\n",
    "\n",
    "# 6. 模型训练\n",
    "try:\n",
    "    nb_clf = GaussianNB()\n",
    "    nb_clf.fit(X_train, y_train)\n",
    "    print(\"\\n模型训练完成！\")\n",
    "    \n",
    "    # 7. 模型评估\n",
    "    y_pred = nb_clf.predict(X_test)\n",
    "    accuracy = accuracy_score(y_test, y_pred)\n",
    "    print(f\"\\n模型准确率: {accuracy:.4f}\")\n",
    "    print(\"\\n详细分类报告:\")\n",
    "    print(classification_report(y_test, y_pred))\n",
    "    \n",
    "except Exception as e:\n",
    "    print(f\"模型训练失败: {str(e)}\")\n",
    "\n",
    "# 8. 特征重要性分析（可选）\n",
    "if hasattr(nb_clf, 'theta_'):\n",
    "    print(\"\\n各类别的特征均值:\")\n",
    "    for i, class_mean in enumerate(nb_clf.theta_):\n",
    "        print(f\"类别 {i}: {class_mean}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cea88231",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
